#include "stdafx.h"
#include "Material.h"
#include "Shader.h"

Material::Material()
{
	m_shader = nullptr;
	m_baseTextureUnit = 0;
	m_depthTestFunc = GL_LESS;
	m_blendSfactor = GL_SRC_ALPHA;
	m_blendDfactor = GL_ONE_MINUS_SRC_ALPHA;
	m_alphaTestFunc = GL_GREATER;
	m_alphaTestRef = 0.9f;
	m_blend = false;
	m_alphaTest = false;
	m_depthTest = true;
	m_enableTextureOffset = false;
	m_textureOffsetXspeed = m_textureOffsetYspeed = 0.f;
}

Material::~Material()
{
}

void Material::Use()
{
	m_shader->UseProgram();
	GLFuncSet();
	BindTextures();
	if (m_enableTextureOffset)
	{
		auto dt = FrameTime::GetInstance()->GetDeltaTime();
		m_materialParams.textureOffset.s += m_textureOffsetXspeed*dt;
		m_materialParams.textureOffset.t += m_textureOffsetYspeed*dt;
	}
	Shaders::GetInstance()->m_uboMaterial.SetMaterial(&this->m_materialParams, true);
}

void Material::SetTextureOffsetSpeed(glm::vec2 &sp)
{
	m_textureOffsetXspeed = sp.x;
	m_textureOffsetYspeed = sp.y;
}

void Material::EnableTextureOffset(bool f)
{
	m_enableTextureOffset = f;
}


void Material::BindTextures()
{
	int i = 0;
	for (auto tex : m_textures)
	{
		tex->Bind(m_baseTextureUnit + i);
		i++;
	}
}

void Material::GLFuncSet()
{
	if (m_depthTest)
	{
		glEnable(GL_DEPTH_TEST);
		glDepthFunc(m_depthTestFunc);
	}
	else glDisable(GL_DEPTH_TEST);

	if (m_alphaTest)
	{
		glEnable(GL_ALPHA_TEST);
		glAlphaFunc(m_alphaTestFunc, m_alphaTestRef);
	}
	else glDisable(GL_ALPHA_TEST);

	if (m_blend)
	{
		glEnable(GL_BLEND);
		glBlendFunc(m_blendSfactor, m_blendDfactor);
	}
	else glDisable(GL_BLEND);
}